<?php
/**
 * oscshop2 B2C电子商务系统
 *
 * ==========================================================================
 * @link      http://www.oscshop.cn/
 * @copyright Copyright (c) 2015-2017 oscshop.cn.
 * @license   http://www.oscshop.cn/license.html License
 * ==========================================================================
 *
 * @author    李梓钿
 *
 * 系统会员相关类
 *
 */
namespace osc\common\service;

use think\Db;
use think\Session;
use think\Loader;

//use SmsDemo;
class Member
{

    //加入收藏
    public function add_wishlist($goods_id, $uid)
    {

        $goods_id = (int)$goods_id;

        if (!Db::name('goods')->where(array('goods_id' => $goods_id, 'status' => 1))->find()) {
            return array('error' => '产品不存在');
        }

        if (!$uid) {
            return array('error' => '请先登录');
        }

        if (!Db::name('member_wishlist')->where(array('uid' => $uid, 'goods_id' => $goods_id))->find()) {
            Db::name('member_wishlist')->insert(array('uid' => $uid, 'goods_id' => $goods_id, 'date_added' => date('Y-m-d H:i:s', time())));
            Db::name('member')->where('uid', $uid)->setInc('wish', 1);
        }

        return array('success' => '收藏成功');
    }

    //删除收藏
    public function remove_wish($id, $uid)
    {
        Db::name('member_wishlist')->where(array('uid' => $uid, 'goods_id' => (int)$id))->delete();
        Db::name('member')->where('uid', $uid)->setDec('wish', 1);
    }

    //会员收藏的商品
    public function get_wishlist($uid, $num)
    {
        if ($uid) {
            return Db::view('Goods', 'goods_id,image,price,name,date_added')
                ->view('MemberWishlist', 'uid', 'Goods.goods_id=MemberWishlist.goods_id')
                ->where(array('MemberWishlist.uid' => $uid))->limit($num)->order('date_added desc')->select();
        }
        return null;
    }

    /**
     * 验证手机号是否正确
     * @param number $mobile
     *    支持类型
     *
     *    移动：134、135、136、137、138、139、150、151、152、157、158、159、182、183、184、187、188、178(4G)、147(上网卡)；
     *
     *    联通：130、131、132、155、156、185、186、176(4G)、145(上网卡)；
     *
     *    电信：133、153、180、181、189 、177(4G)；
     *
     *    卫星通信：1349
     *
     *    虚拟运营商：170
     */
    function isMobile($mobile)
    {
        if (!is_numeric($mobile)) {
            return false;
        }

        return preg_match('#^13[\d]{9}$|^17[\d]{9}$|^19[\d]{9}$|^14[\d]{9}$|^16[\d]{9}$|^15[\d]{9}$|^17[\d]{9}$|^18[\d]{9}$#', $mobile) ? true : false;
    }

    //会员绑定微信号
    function bind_weixin($uid, $user_info)
    {

        if (empty($user_info) || empty($uid)) {
            return false;
        }

        Db::name('member')->where('uid', $uid)->update(array(
            'wechat_openid' => $user_info['openid'],
            'nickname' => $user_info['nickname'],
            'sex' => $user_info['sex'],
            'userpic' => $user_info['headimgurl']
        ), false, true);

        $user['uid'] = $uid;
        $user['openid'] = $user_info['openid'];
        $user['username'] = $user_info['nickname'];
        $user['sex'] = $user_info['sex'];
        $user['userpic'] = $user_info['headimgurl'];

        cookie('member_user_auth', $user);

    }

    //保存会员信息到cookie
    function refresh_member($member)
    {
        if (empty($member) && !is_array($member)) {
            return;
        }

        cookie('member_user_auth', $member, 3600 * 7);
        cookie('member_user_auth_sign', data_auth_sign($member), 3600 * 7);
    }

    //验证推荐码是否存在
    function isShareMobile($code)
    {

        $member = model('member');

        $left_code = $member->where('left_code', $code)->find();

        $right_code = $member->where('right_code', $code)->find();

        if ($left_code || $right_code) {
            return true;
        } else {
            return false;
        }
    }

    //验证服务中心
    function isService($code){

        $agent = model('agent');
        $service_code = $agent->where('service_code',$code)->find();

        if($service_code){
            return true;
        }else{
            return false;
        }

    }


    //注册验证等相关操作
    function reg($data)
    {

        $validate = Loader::validate('UserInfo');

        if (!$validate->scene('register')->check($data)) {
            //throw new \Exception($validate->getError());
            return array('error' => $validate->getError());
        }

        /*if (!$this->isMobile($data['username'])) {
            return array('error' => '请输入正确的手机号码');
        }*/

        //验证推荐人
        $isShareCode = $this->isShareMobile($data['sharemobile']);

        if (!$isShareCode) return array('error' => '推荐人不存在');

        //验证服务中心
        $isServiceCode = $this->isService($data['service_code']);

        if (!$isServiceCode) return array('error' => '服务中心不存在');


        $user = Db::name('member')->where('username', $data['username'])->find();

        if ($user) {
            return array('error' => '用户已经注册');
        }

        $member['sharemobile'] = $data['sharemobile'];
        $member['service_agent'] = $data['service_code'];
        $member['nickname'] = $data['nickname'];
        $member['password'] = think_ucenter_encrypt($data['password'], config('PWD_KEY'));
        $member['2password'] = think_ucenter_encrypt($data['2password'], config('PWD_KEY'));
        $member['username'] = $data['username'];
        $member['groupid'] = config('default_group_id');

        if (in_wechat()) {
            $member['reg_type'] = 'weixin';
        } elseif (request()->isMobile()) {
            $member['reg_type'] = 'mobile';
        } else {
            $member['reg_type'] = 'pc';
        }

        $member['regdate'] = time();
        $member['lastdate'] = time();
        $member['nickname'] = $data['nickname'];

        if (1 == config('reg_check')) {//需要审核或者验证
            $member['checked'] = 0;
        } else {
            $member['checked'] = 1;
        }

//        echo'<pre>';print_r($data);
//        echo'<pre>';print_r($member);
//        exit;

        $uid = Db::name('member')->insert($member, false, true);
        session("SMS", null);

        if ($uid) {

            if (in_wechat()) {
                $this->bind_weixin($uid, cookie('weixin_user_info'));
            }

            //写入用户权限表
//			Db::name('member_auth_group_access')->insert(array('uid'=>$uid,'group_id'=>$member['groupid']),false,true);
//			print_r($member);exit;

            if (1 == config('reg_check')) {//需要审核
                return array('success' => '注册成功，请等待管理员审核', 'check' => 1);
            } else {//不需要审核
                $auth = array(
                    'uid' => $uid,
                    'username' => $member['username'],
                    'nickname' => $member['nickname'],
                    'group_id' => $member['groupid'],
                );

                $this->refresh_member($auth);

                session("username", $data['username']);

                storage_user_action($uid, $member['username'], config('FRONTEND_USER'), '注册成为会员');

                return array('success' => '注册成功', 'check' => 0, 'username' => $member['username']);
            }

        } else {
            return array('error' => '注册失败');
        }
    }

    function find($data)
    {

        //找回密码
        if (!$this->isMobile($data['username'])) {
            return array('error' => '请输入正确的手机号码');
        }


        $user = Db::name('member')->where('username', $data['username'])->find();

        if (!$user) {
            return array('error' => '手机号不存在');
        }


        $validate = Loader::validate('UserInfo');

        if (!$validate->scene('find')->check($data)) {
            //throw new \Exception($validate->getError());
            return array('error' => $validate->getError());
        }

        //验证短信验证码
        $smscode = session("FINDSMS");
        if ($smscode != $data['code']) {
            return array('error' => '手机验证码错误');
        }

        $smsusername = $data['username'] . "FINDSMS";
        if (!$data['username'] == session($smsusername)) {
            return array('error' => '手机验证码错误');
        }

        //更新用户密码
        $member['password'] = think_ucenter_encrypt($data['password'], config('PWD_KEY'));
        $member['username'] = $data['username'];
        $uid = Db::name('member')->where('username', $member['username'])->update($member);
        session("FINDSMS", null);
        storage_user_action($uid, $member['username'], config('FRONTEND_USER'), '修改密码');


    }


    //登录验证等相关操作
    function api_login($data)
    {

        if (!$this->isMobile($data['username'])) {
            return array('code' => -1, 'error' => '请输入正确的手机号码');
        }
        if (empty($data['password'])) {
            return array('code' => -1, 'error' => '密码必填');
        }

        if (1 == config('use_captcha')) {
            if (!check_verify($data['captcha'])) {
                return array('code' => -1, 'error' => '验证码错误');
            }
        }

        $user = Db::name('member')->where('username', $data['username'])->find();

        if (!$user) {
            return array('error' => '手机号不存在');
        } elseif (($user['checked'] == 0) && (1 == config('reg_check'))) {//需要审核
            return array('code' => -1, 'error' => '该手机号未审核通过');
        }
        if (think_ucenter_encrypt($data['password'], config('PWD_KEY')) == $user['password']) {


            $login['lastdate'] = time();
            $login['loginnum'] = array('exp', 'loginnum+1');
            $login['lastip'] = get_client_ip();

            DB::name('member')->where('uid', $user['uid'])->update($login);

            storage_user_action($user['uid'], $user['username'], config('FRONTEND_USER'), '登录了网站');

            $data = [
                'uid' => think_ucenter_encrypt($user['uid'], config('PWD_KEY')),
                'username' => think_ucenter_encrypt($user['username'], config('PWD_KEY')),
                'nickname' => $user['nickname']
            ];


            return array('code' => 1, 'success' => '登录成功', 'data' => $data);
        } else {
            return array('code' => 0, 'error' => '密码错误');
        }

    }


    //登录验证等相关操作
    function login($data)
    {

        if (!$this->isMobile($data['username'])) {
            return array('error' => '请输入正确的手机号码');
        }
        if (empty($data['password'])) {
            return array('error' => '密码必填');
        }

        if (1 == config('use_captcha')) {
            if (!check_verify($data['captcha'])) {
                return array('error' => '验证码错误');
            }
        }

        $user = Db::name('member')->where('username', $data['username'])->find();

        if (!$user) {
            return array('error' => '手机号不存在');
        } elseif (($user['checked'] == 0) && (1 == config('reg_check'))) {//需要审核
            return array('error' => '该手机号未审核通过');
        }


        if (think_ucenter_encrypt($data['password'], config('PWD_KEY')) == $user['password']) {

            $auth = array(
                'uid' => $user['uid'],
                'username' => $user['username'],
                'nickname' => $user['nickname'],
                'group_id' => $user['groupid'],
            );

            $this->refresh_member($auth);

            $login['lastdate'] = time();
            $login['loginnum'] = array('exp', 'loginnum+1');
            $login['lastip'] = get_client_ip();

            DB::name('member')->where('uid', $user['uid'])->update($login);
            storage_user_action($user['uid'], $user['username'], config('FRONTEND_USER'), '登录了网站');


            //绑定微信
            if (empty($user['wechat_openid']) && in_wechat()) {
                osc_service('common', 'Member')->bind_weixin($user['uid'], cookie('weixin_user_info'));
            }

            return array('success' => '登录成功', 'username' => $user['username'], 'total' => osc_cart()->count_cart_total($user['uid']));
        } else {
            return array('error' => '密码错误');
        }

    }

    /**
     * 修改密码
     * @param $data
     * @return array
     * @throws \think\Exception
     */
    function api_updateuserpasswd($data)
    {
        //解密
        $uid = think_ucenter_decrypt($data['uid'], config('PWD_KEY'));

        $oldpassword = think_ucenter_encrypt($data['oldpassword'], config('PWD_KEY'));
        $member['password'] = think_ucenter_encrypt($data['password'], config('PWD_KEY'));

        $user = Db::name('member')->where('uid', $uid)->where('password', $oldpassword)->find();
        if ($user) {
            $res = Db::name('member')->where('username', $user['username'])->update($member);

            if ($res) {
                storage_user_action($uid, $user['username'], config('FRONTEND_USER'), '修改密码');

                return array('code' => 1, 'success' => 'OK');
            }
            return array('code' => 0, 'error' => '修改失败');
        } else {
            return array('code' => 0, 'error' => '旧密码错误');
        }

    }

    /**
     * 修改密码
     * @param $data
     * @return array
     * @throws \think\Exception
     */
    function updateuserpasswd($data)
    {
        $username = session("username");

        $validate = Loader::validate('UserInfo');

        if (!$validate->scene('updatepasswd')->check($data)) {
            //throw new \Exception($validate->getError());
            return array('error' => $validate->getError());
        }

        $oldpassword = think_ucenter_encrypt($data['oldpassword'], config('PWD_KEY'));
        $member['password'] = think_ucenter_encrypt($data['password'], config('PWD_KEY'));

        $user = Db::name('member')->where('username', $username)->where('password', $oldpassword)->find();
        if ($user) {
            $uid = Db::name('member')->where('username', $username)->update($member);
            storage_user_action($uid, $username, config('FRONTEND_USER'), '修改密码');
        } else {
            return array('error' => '密码错误');
        }

    }

    function updateuser2passwd($data)
    {
        $username = session("username");

        $validate = Loader::validate('UserInfo');

        if (!$validate->scene('update2passwd')->check($data)) {
            //throw new \Exception($validate->getError());
            return array('error' => $validate->getError());
        }

        /*$code = session("send2pwd");
        if (!$code == $data['code']) {
            return array('error' => '手机验证码输入错误');
        }

        $smsusername = $username . "send2pwd";
        if (session($smsusername) != $username) {
            return array('error' => '手机验证码输入错误');
        }*/

        $oldpassword = think_ucenter_encrypt($data['password'], config('PWD_KEY'));
        $member['2password'] = think_ucenter_encrypt($data['2password'], config('PWD_KEY'));

        $user = Db::name('member')->where('username', $username)->where('password', $oldpassword)->find();
        if ($user) {
            $uid = Db::name('member')->where('username', $username)->update($member);
            storage_user_action($uid, $username, config('FRONTEND_USER'), '修改二级密码');
        } else {
            session("send2pwd", null);
            return array('error' => '登录密码错误');

        }

    }

    function updateidcard($data)
    {

        $username = session("username");

        $validate = Loader::validate('UserInfo');
        //$uid = islogin();

        $user = Db::name('member')->where('username', $username)->find();
        $card = Db::name('member')->where('idcard', $data['idcard'])->find();

        if ($card) {
            return array('error' => '该身份证号码已经被使用');
        }
        if ($user['isauth'] != 0) {
            return array('error' => '该用户已经实名认证');
        }

        $result = $this->getarea($data['idcard']);


        $area = null;
        if ($result['error_code'] == '0') {
            $area = $result['result']['area'];
        }
        /*
        else
        {
        	return array('error'=>'您填写的身份证号码有误！');
        }
        */
        //var_dump($area);

        storage_user_action($user['uid'], $username, config('FRONTEND_USER'), '用户进行实名认证');
        $member['idcardname'] = $data['idcardname'];
        $member['idcard'] = $data['idcard'];
        $member['id6'] = substr($data['idcard'], 0, 6);
        $member['area'] = $area;
        $member['isauth'] = 1;
        $uid = Db::name('member')->where('username', $username)->update($member);

    }


    function getarea($cardno)
    {
        header('Content-type:text/html;charset=utf-8');


        //配置您申请的appkey
        $appkey = "2bc06ad0c2f9ead55f58fb46ced18193";


        //************1.身份证信息查询************
        $url = "http://apis.juhe.cn/idcard/index";
        $params = array(
            "cardno" => "$cardno",//身份证号码
            "dtype" => "",//返回数据格式：json或xml,默认json
            "key" => $appkey,//你申请的key
        );
        $paramstring = http_build_query($params);
        $content = $this->juhecurl($url, $paramstring);
        $result = json_decode($content, true);

        return $result;

    }

    /**
     * 请求接口返回内容
     * @param  string $url [请求的URL地址]
     * @param  string $params [请求的参数]
     * @param  int $ipost [是否采用POST形式]
     * @return  string
     */
    function juhecurl($url, $params = false, $ispost = 0)
    {
        $httpInfo = array();
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        curl_setopt($ch, CURLOPT_USERAGENT, 'JuheData');
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        if ($ispost) {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
            curl_setopt($ch, CURLOPT_URL, $url);
        } else {
            if ($params) {
                curl_setopt($ch, CURLOPT_URL, $url . '?' . $params);
            } else {
                curl_setopt($ch, CURLOPT_URL, $url);
            }
        }
        $response = curl_exec($ch);
        if ($response === FALSE) {
            //echo "cURL Error: " . curl_error($ch);
            return false;
        }
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $httpInfo = array_merge($httpInfo, curl_getinfo($ch));
        curl_close($ch);
        return $response;
    }

    /**
     * 银行卡信息绑定
     * @param $data
     * @return array
     * @throws \think\Exception
     */
    function updatebank($data)
    {

        $username = session("username");

        $validate = Loader::validate('UserInfo');

        if (!$validate->scene('bank')->check($data)) {
            //throw new \Exception($validate->getError());
            return array('error' => $validate->getError());
        }

        /*$code = session("updatebank");
        if (!$code == $data['code']) {
            return array('error' => '手机验证码输入错误');
        }*/


        $bank['username'] = $username;
        $bank['bankname'] = $data['bankname'];
        $bank['bankaccountname'] = $data['bankaccountname'];
        $bank['subbankname'] = $data['subbankname'];
        $bank['bankaccount'] = $data['bankaccount'];

        $user = Db::name('user_bank')->where('username', $username)->find();
        if ($user) {
            //update
            $uid = Db::name('user_bank')->where('username', $username)->update($bank);
        } else {
            $user = Db::name('user_bank')->insert($bank);

        }
        session("updatebank", null);

    }

    /**
     * 可用额度转金豆
     * @param $data
     * @return array
     */
    function can_gold($data)
    {

        $username = session("username");
        $curruser = Db::name('member')->where('username', $username)->find();

        //var_dump($senduser);

        if (!is_numeric($data['num'])) {
            return array('error' => '转入金额请输入数字');
        }

        if ($data['num'] % 100 != 0) {
            return array('error' => '请输入100的整数倍');
        }

        if ($curruser['can_quota'] < $data['num']) {
            return array('error' => '可用额度不够');
        }
        $data['username'] = $username;
        unset($data['__token__']);
//		print_r($data);;exit;
        Db::startTrans();
        try {

            $user = Db::name('can_gold')->insert($data);


            $user = Db::name('member')->where('username', $username)->setDec('can_quota', $data['num']);
            $user = Db::name('member')->where('username', $username)->setInc('predeposit', $data['num']);

            Db::commit();
            return array('success' => '可用余额转金豆成功', 'url' => '/mobile');

        } catch (\Exception $e) {
            Db::rollback();
            return array('error' => $e->getMessage());
        }

    }


    /**
     * 金豆A转B
     * @param $data
     * @return array
     */
    function pointstf($data)
    {

        $username = session("username");
        $curruser = Db::name('member')->where('username', $username)->find();

        //var_dump($senduser);

        if (!is_numeric($data['num'])) {
            return array('error' => '转入金额请输入数字');
        }
        if ($curruser['b2_predeposit'] < $data['num']) {
            return array('error' => '可用额度不够');
        }
        $data['username'] = $username;

        $data1['username'] = $username;

        $data1['num'] = $data['num'];
        $data1['token'] = $data['token'];
        Db::startTrans();
        try {

            $user = Db::name('pointstf')->insert($data1);
            $curruser = Db::name('member')->where('username', $username)->find();

            $befor = (int)$curruser['b2_predeposit'];
            $after = (int)$curruser['b2_predeposit'] - $data['num'];
            Db::name('predeposit')->insert(array(
                'uid' => $curruser['uid'],
                'username' => $username,
                'money' => $data['num'],
                'description' => 'A金豆转B金豆,转出前A金豆数量' . $befor . '转出后A金豆数量' . $after,
                'prefix' => 2,
                'creat_time' => time(),
                'pay_time' => time(),
                'pay_status' => 1
            ));

            $befor = (int)$curruser['predeposit'];
            $after = (int)$curruser['predeposit'] + $data['num'];
            Db::name('prepoint')->insert(array(
                'uid' => $curruser['uid'],
                'username' => $username,
                'money' => $data['num'],
                'description' => 'A金豆转B金豆,转入前B金豆数量' . $befor . '转入后B金豆数量' . $after,
                'prefix' => 2,
                'creat_time' => time(),
                'pay_time' => time(),
                'pay_status' => 1
            ));

            $user = Db::name('member')->where('username', $username)->setDec('b2_predeposit', $data['num']);
            $user = Db::name('member')->where('username', $username)->setInc('predeposit', $data['num']);

            Db::commit();
            return array('success' => 'A金豆转B金豆成功', 'url' => '/mobile');

        } catch (\Exception $e) {
            Db::rollback();
            return array('error' => $e->getMessage());
        }

    }

    /**
     * 用户金豆转让
     * @param $data
     * @return array
     */
    function usertf($data)
    {

        $username = session("username");
        $curruser = Db::name('member')->where('username', $username)->find();

        $n = $data['num'];
        //var_dump($n);
        /*
        if(is_int($n))
        {
            return array('error'=>'转让数量必须输入整数!');
        }
        */
        $validate = Loader::validate('UserInfo');
        if (!$validate->scene('goldstone')->check($data)) {
            //throw new \Exception($validate->getError());
            return array('error' => $validate->getError());
        }
        $senduser = Db::name('member')->where('username', $data['mobile'])->find();
        $pwd2 = think_ucenter_encrypt($data['pwd2'], config('PWD_KEY'));


        $user = Db::name('member')->where('username', $username)->find();

        if ($pwd2 != $user['2password']) {
            return array('error' => '二级密码输入有误');
        }
        //var_dump($senduser);
        if (is_null($senduser)) {
            return array('error' => '用户不存在');
        }

        if ($curruser['card'] < $data['num']) {
            return array('error' => '可用额度不够');
        }
        $data['username'] = $username;

        $data1['username'] = $username;
        $data1['mobile'] = $data['mobile'];
        $data1['nickname'] = $senduser['nickname'];
        $data1['num'] = $data['num'];
        $data1['token'] = $data['token'];
        Db::startTrans();
        try {
            $user = Db::name('usertf')->insert($data1);

            $user = Db::name('member')->where('username', $username)->setDec('card', $data['num']);
            $user = Db::name('member')->where('username', $data['mobile'])->setInc('card', $data['num']);

            $curruser = Db::name('member')->where('username', $username)->find();

            //var_dump($data);
            Db::commit();
            return array('success' => '提交转让成功', 'url' => '/mobile');

        } catch (\Exception $e) {

            Db::rollback();
            return array('error' => $e->getMessage());

        }


    }

    /**
     * 元宝转让
     * @param $data
     * @return array
     */
    function jilin_usertf($data)
    {

        $username = session("username");
        $curruser = Db::name('member')->where('username', $username)->find();

        $validate = Loader::validate('UserInfo');
        if (!$validate->scene('goldstone')->check($data)) {
            //throw new \Exception($validate->getError());
            return array('error' => $validate->getError());
        }
        $senduser = Db::name('member')->where('username', $data['mobile'])->find();
        $pwd2 = think_ucenter_encrypt($data['pwd2'], config('PWD_KEY'));


        $user = Db::name('member')->where('username', $username)->find();

        if ($pwd2 != $user['2password']) {
            return array('error' => '二级密码输入有误');
        }

        if (is_null($senduser)) {
            return array('error' => '用户不存在');
        }

        if ($curruser['jilin_bean'] < $data['num']) {
            return array('error' => '可用额度不够');
        }

        $map = [
            'token' => $data['token'],
            'username' => $username,
            'mobile' => $data['mobile'],
            'nickname' => $senduser['nickname'],
            'num' => $data['num'],
            'actual_num' => $data['num'] - ($data['num'] * 0.05),
            'rate' => $data['num'] * 0.05,
        ];

        Db::startTrans();
        try {

            Db::name('jilin_usertf')->insert($map);

            Db::name('member')->where('username', $username)->setDec('jilin_bean', $map['num']);
            Db::name('member')->where('username', $data['mobile'])->setInc('jilin_bean', $map['actual_num']);

            Db::commit();
            return array('success' => '提交转让成功', 'url' => '/mobile');

        } catch (\Exception $e) {

            Db::rollback();
            return array('error' => $e->getMessage());

        }

    }


    function wd($data)
    {

        $username = session("username");
        $uid = is_login();

        $validate = Loader::validate('UserInfo');


        if (!$username) {
            return array('error' => '获取用户信息失败');
        }

        if (!$validate->scene('goldstone')->check($data)) {
            //throw new \Exception($validate->getError());
            return array('error' => $validate->getError());
        }
        //var_dump($data);


        $pwd2 = think_ucenter_encrypt($data['pwd2'], config('PWD_KEY'));


        $user = Db::name('member')->where('username', $username)->find();

        if ($pwd2 != $user['2password']) {
            return array('error' => '二级密码输入有误');
        }


        $bank = Db::name('user_bank')->where('username', $username)->find();
        if (!$bank) {
            return array('error' => '您还没有设置银行账号!');
        }

        //必须是100的整数倍
        if ($data['num'] % 100 > 0) {
            return array('error' => '兑换数量必须是100的整数倍!');
        }

        $befor = (int)$user['predeposit'];
        $after = (int)$user['predeposit'] - $data['num'];
        if ($after < 0) {
            return array('error' => '您的可用额度不够!');
        }
        //事务开始
        Db::startTrans();
        //var_dump($bank);
        $goldstone['username'] = $username;
        $goldstone['token'] = $data['token'];
        $goldstone['num'] = $data['num'];
        $goldstone['creat_time'] = time();
        $goldstone['money'] = $goldstone['num'];
        $goldstone['real_money'] = $goldstone['money'] * 0.95;
        $goldstone['description'] = '金豆兑换';
        $goldstone['bankname'] = $bank['bankname'] . $bank['subbankname'];
        $goldstone['bankaccountname'] = $bank['bankaccountname'];
        $goldstone['bankaccount'] = $bank['bankaccount'];


        $goldstoneinfo['username'] = $goldstone['username'];
        $goldstoneinfo['num'] = $goldstone['num'];
        $goldstoneinfo['creat_time'] = $goldstone['creat_time'];
        $goldstoneinfo['description'] = '提交兑换,兑换前金豆数量' . $befor . '兑换后金豆数量' . $after;


        Db::name('predeposit')->insert(array(
            'uid' => $user['uid'],
            'username' => $goldstone['username'],
            'order_id' => '',
            'order_num_alias' => '',
            'money' => $goldstone['num'],
            'description' => '金豆兑换,兑换前金豆数量' . $befor . '兑换后金豆数量' . $after,
            'prefix' => 2,
            'creat_time' => time(),
            'pay_time' => time(),
            'pay_status' => 1
        ));


        try {
            //var_dump($goldstone);
            $user = Db::name('goldstonewd')->insert($goldstone);
            //var_dump($user);
            $user = Db::name('goldstone')->insert($goldstoneinfo);
            $user = Db::name('member')->where('username', $goldstone['username'])->setDec('predeposit', $goldstone['num']);
            $user = Db::name('member')->where('username', $goldstone['username'])->setInc('use_predeposit', $goldstone['num']);
            storage_user_action($uid, $username, config('FRONTEND_USER'), '用户提现');
            Db::commit();
        } catch (\Exception $e) {

            Db::rollback();
            return array('error' => $e->getMessage());

        }

    }

    function tf($data)
    {

        $username = session("username");
        $uid = is_login();

        $validate = Loader::validate('UserInfo');
        if (!$username) {
            return array('error' => '获取用户信息失败');
        }

        if (!$validate->scene('goldstone')->check($data)) {
            //throw new \Exception($validate->getError());
            return array('error' => $validate->getError());
        }

        //事务开始
        Db::startTrans();
        $user = Db::name('member')->where('username', $username)->find();
        $pre_bala = $data['num'] * 200;
        if ($user['balance_acc'] < $pre_bala) {
            return array('error' => '您的可以额度不够!');
        }


        $accounttf['username'] = $username;
        $accounttf['token'] = $data['token'];
        $accounttf['num'] = $data['num'];
        $accounttf['creat_time'] = time();
        $accounttf['money'] = 200 * $data['num'];
        $accounttf['description'] = '转巨能果';

        $goldstoneinfo['username'] = $username;
        $goldstoneinfo['num'] = $data['num'];
        $goldstoneinfo['creat_time'] = time();
        $goldstoneinfo['description'] = '奖励积分转巨能果';

        try {

            $user = Db::name('account_tf')->insert($accounttf);
            $user = Db::name('goldstone')->insert($goldstoneinfo);

            $user = Db::name('member')->where('username', $username)->setDec('balance_acc', $accounttf['money']);
            $user = Db::name('member')->where('username', $username)->setInc('goldstone', $accounttf['num']);
            storage_user_action($uid, $username, config('FRONTEND_USER'), '奖励积分转巨能果');
            Db::commit();
        } catch (\Exception $e) {

            Db::rollback();
            return array('error' => $e->getMessage());

        }

    }

    function agent_tf($data)
    {

        $username = session("username");
        $uid = is_login();

        $validate = Loader::validate('UserInfo');
        if (!$username) {
            return array('error' => '获取用户信息失败');
        }

        if (!$validate->scene('goldstone')->check($data)) {
            //throw new \Exception($validate->getError());
            return array('error' => $validate->getError());
        }

        //事务开始
        Db::startTrans();
        $user = Db::name('member')->where('username', $username)->find();
        $pre_bala = $data['num'] * 200;
        if ($user['agent_balance_acc'] < $pre_bala) {
            return array('error' => '您的可以额度不够!');
        }


        $accounttf['username'] = $username;
        $accounttf['token'] = $data['token'];
        $accounttf['num'] = $data['num'];
        $accounttf['creat_time'] = time();
        $accounttf['money'] = 200 * $data['num'];
        $accounttf['description'] = '转巨能果';

        $goldstoneinfo['username'] = $username;
        $goldstoneinfo['num'] = $data['num'];
        $goldstoneinfo['creat_time'] = time();
        $goldstoneinfo['description'] = '代理奖励积分转巨能果';

        try {

            $user = Db::name('agent_account_tf')->insert($accounttf);
            $user = Db::name('goldstone')->insert($goldstoneinfo);

            $user = Db::name('member')->where('username', $username)->setDec('agent_balance_acc', $accounttf['money']);
            $user = Db::name('member')->where('username', $username)->setInc('goldstone', $accounttf['num']);
            storage_user_action($uid, $username, config('FRONTEND_USER'), '代理奖励积分转巨能果');
            Db::commit();
        } catch (\Exception $e) {

            Db::rollback();
            return array('error' => $e->getMessage());

        }

    }

    function stone_goldstone($data)
    {
        $username = session("username");
        $uid = is_login();

        $validate = Loader::validate('UserInfo');
        if (!$username) {
            return array('error' => '获取用户信息失败');
        }

        if (!$validate->scene('stone')->check($data)) {
            //throw new \Exception($validate->getError());
            return array('error' => $validate->getError());
        }

        $pwd2 = think_ucenter_encrypt($data['pwd2'], config('PWD_KEY'));


        $user = Db::name('member')->where('username', $username)->find();

        if ($pwd2 != $user['2password']) {
            return array('error' => '二级密码输入有误');
        }

        //事务开始
        Db::startTrans();
        $user = Db::name('member')->where('username', $username)->find();
        $stone = Db::name('stone')->where('id', $data['id'])->find();

        if (!$stone) {
            return array('error' => '获取信息失败');
        }
        if ($stone['state'] == 1) {
            return array('error' => '获取信息失败');
        }

        $pre_bala = $data['num'] * $stone['curr_price'];
        if (($user['goldstone'] * 200) < ($pre_bala * 0.9)) {
            return array('error' => '您的可以额度不够!');
        }

        $num = ceil(($pre_bala * 0.9) / 200);

        //$remainder = (($user['goldstone']*200 - ($pre_bala*0.9))/0.9;
        $remainder = $num * 200 - $pre_bala * 0.9;
        $remainder = $remainder * 1.1;


        try {

            $stone_position = Db::name('stone_position')->where('username', $username)->find();
            if ($stone_position) {
                //update
                $ret = Db::name('stone_position')->where('username', $username)->setInc('position', $remainder);
            } else {
                //insert
                $sp['position'] = $remainder;
                $sp['username'] = $username;
                $sp['creat_time'] = time();
                $sp['use_position'] = 0;
                $ret = Db::name('stone_position')->insert($sp);

            }

            $user_stone = Db::name('user_stone')->where('username', $username)->where('stone_id', $data['id'])->find();


            if ($user_stone) {
                $ret = Db::name('user_stone')->where('username', $username)->where('stone_id', $data['id'])->setInc('num', $data['num']);
            } else {
                $us['username'] = $username;
                $us['num'] = $data['num'];
                $us['stone_name'] = $stone['name'];
                $us['stone_id'] = $data['id'];
                $us['creat_time'] = time();

                $ret = Db::name('user_stone')->insert($us);

            }

            //减掉金石
            $ret = Db::name('member')->where('username', $username)->setDec('goldstone', $num);


            $stoneinfo['username'] = $username;
            $stoneinfo['num'] = $data['num'];
            $stoneinfo['money'] = $num;
            $stoneinfo['last_money'] = $remainder;
            $stoneinfo['creat_time'] = time();
            $stoneinfo['token'] = $data['token'];
            $stoneinfo['description'] = '巨能果增值买入价' . $stone['curr_price'];

            //var_dump($stoneinfo);
            $user = Db::name('stone_goldstone_tf')->insert($stoneinfo);


            storage_user_action($uid, $username, config('FRONTEND_USER'), '巨能果增值' . $stone['name']);
            Db::commit();
            //return array('sucess'=>'操作成功!');
        } catch (\Exception $e) {

            Db::rollback();
            return array('error' => $e->getMessage());

        }
    }


    function stone_sell($data)
    {
        $username = session("username");
        $uid = is_login();

        $validate = Loader::validate('UserInfo');
        if (!$username) {
            return array('error' => '获取用户信息失败');
        }

        if (!$validate->scene('stone')->check($data)) {
            //throw new \Exception($validate->getError());
            return array('error' => $validate->getError());
        }

        $pwd2 = think_ucenter_encrypt($data['pwd2'], config('PWD_KEY'));


        $user = Db::name('member')->where('username', $username)->find();

        if ($pwd2 != $user['2password']) {
            return array('error' => '二级密码输入有误');
        }

        //事务开始
        Db::startTrans();
        $user = Db::name('member')->where('username', $username)->find();
        $stone = Db::name('stone')->where('id', $data['id'])->find();

        if (!$stone) {
            return array('error' => '获取信息失败');
        }

        if ($stone['state'] == 1) {
            return array('error' => '获取信息失败');
        }

        $userstone = Db::name('user_stone')->where('stone_id', $data['id'])->find();

        if ($userstone['num'] < $data['num']) {
            return array('error' => '提交的数量超过了用户持有数量');
        }

        //
        $predeposit = $stone['curr_price'] * $data['num'];

        try {
            //减掉用户的份额

            $ret = Db::name('user_stone')->where('username', $username)->where('stone_id', $data['id'])->setDec('num', $data['num']);


            $stone_position = Db::name('stone_position')->where('username', $username)->find();
            if ($stone_position) {
                //update
                $ret = Db::name('stone_position')->where('username', $username)->setInc('position', $predeposit);
            } else {
                //insert
                $sp['position'] = $predeposit;
                $sp['username'] = $username;
                $sp['creat_time'] = time();
                $sp['use_position'] = 0;
                $ret = Db::name('stone_position')->insert($sp);

            }


            $stoneinfo['username'] = $username;
            $stoneinfo['num'] = $data['num'];
            $stoneinfo['position'] = $predeposit;
            $stoneinfo['price'] = $stone['curr_price'];
            $stoneinfo['creat_time'] = time();
            $stoneinfo['token'] = $data['token'];
            $stoneinfo['description'] = '交易价格' . $stone['curr_price'];

            //var_dump($stoneinfo);
            $user = Db::name('stone_position_tf')->insert($stoneinfo);


            storage_user_action($uid, $username, config('FRONTEND_USER'), '增值出售' . $stone['name']);
            Db::commit();
            //return array('sucess'=>'操作成功!');
        } catch (\Exception $e) {

            Db::rollback();
            return array('error' => $e->getMessage());

        }
    }

    function sendsms_common1($mobile, $sess)
    {
        $target = "https://sms.aliyuncs.com/?";


        //$withdraw = M('Withdraw');
        //$member = M('Member');
        //查找member_id对应的交易密码
        //$where['member_id'] = session('USER_KEY_ID');
        //查找member表uid对应信息（交易密码，可以金额，冻结金额）
        //$mem_data = $member->field('phone')->where($where)->find();
        $phone = $mobile;

        if (($phone != null) || ($phone != '')) {
            $target = "https://sms.aliyuncs.com/?";

            $mobile_code = $this->random(6, 1);
            // 注意使用GMT时间
            date_default_timezone_set("GMT");
            $dateTimeFormat = 'Y-m-d\TH:i:s\Z'; // ISO8601规范
            $accessKeyId = 'LTAICBmlEOvwfsJd';      // 这里填写您的Access Key ID
            $accessKeySecret = 'zC51CTlzLPne09rO9tIFcJAaH6mrGP';  // 这里填写您的Access Key Secret
            $ParamString = "{\"sms\":\"" . strval($mobile_code) . "\"}";
            session($sess, strval($mobile_code));
            $smsusername = $mobile . $sess;
            session($smsusername, $mobile);
            $data = array(
                // 公共参数
                'SignName' => '茶马古道农业发展',
                'Format' => 'XML',
                'Version' => '2016-09-27',
                'AccessKeyId' => $accessKeyId,
                'SignatureVersion' => '1.0',
                'SignatureMethod' => 'HMAC-SHA1',
                'SignatureNonce' => uniqid(),
                'Timestamp' => date($dateTimeFormat),
                // 接口参数
                'Action' => 'SingleSendSms',
                'TemplateCode' => 'SMS_86070013',
                'RecNum' => $phone,
                'ParamString' => $ParamString
            );
            // 计算签名并把签名结果加入请求参数
            //echo $data['Version']."<br>";
            //echo $data['Timestamp']."<br>";
            $data['Signature'] = $this->computeSignature($data, $accessKeySecret);
            // 发送请求
            $result = $this->xml_to_array($this->https_request($target . http_build_query($data)));
        }
    }

    /**
     * 发送短信验证码接口
     * @param $mobile
     * @param $sess
     * @return stdClass
     */
    function api_sendsms_common($mobile, $sess)
    {
        set_time_limit(0);
        header('Content-Type: text/plain; charset=utf-8');
        $mobile_code = $this->random(6, 1);
        session('mobile_code', $mobile_code);
        $mobile_code = strval($mobile_code);
        $response = SmsDemo::sendSms($mobile, $sess, $mobile_code);

        return ['code' => $mobile_code, 'Message' => $response->Message, 'check' => 1];
    }

    /**
     * 发送短信验证码
     * @param $mobile
     * @param $sess
     * @return stdClass
     */
    function sendsms_common($mobile, $sess)
    {
        set_time_limit(0);
        header('Content-Type: text/plain; charset=utf-8');
        $mobile_code = $this->random(6, 1);
        session($sess, strval($mobile_code));
        $smsusername = $mobile . $sess;
        session($smsusername, $mobile);
        $mobile_code = strval($mobile_code);
        $response = SmsDemo::sendSms($mobile, $sess, $mobile_code);

        /*
        echo "发送短信(sendSms)接口返回的结果:\n";
        print_r($response);

        sleep(2);

        $response = SmsDemo::querySendDetails();
        echo "查询短信发送情况(querySendDetails)接口返回的结果:\n";
        print_r($response);
        */
        //var_dump($response);
        return $response;
    }


    function random($length = 6, $numeric = 0)
    {
        PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);
        if ($numeric) {
            $hash = sprintf('%0' . $length . 'd', mt_rand(0, pow(10, $length) - 1));
        } else {
            $hash = '';
            $chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789abcdefghjkmnpqrstuvwxyz';
            $max = strlen($chars) - 1;
            for ($i = 0; $i < $length; $i++) {
                $hash .= $chars[mt_rand(0, $max)];
            }
        }
        return $hash;
    }


    function percentEncode($str)
    {
        // 使用urlencode编码后，将"+","*","%7E"做替换即满足ECS API规定的编码规范
        $res = urlencode($str);
        $res = preg_replace('/\+/', '%20', $res);
        $res = preg_replace('/\*/', '%2A', $res);
        $res = preg_replace('/%7E/', '~', $res);
        return $res;
    }


    function computeSignature($parameters, $accessKeySecret)
    {
        // 将参数Key按字典顺序排序
        ksort($parameters);
        // 生成规范化请求字符串
        $canonicalizedQueryString = '';
        foreach ($parameters as $key => $value) {
            $canonicalizedQueryString .= '&' . $this->percentEncode($key)
                . '=' . $this->percentEncode($value);
        }
        // 生成用于计算签名的字符串 stringToSign
        $stringToSign = 'GET&%2F&' . $this->percentencode(substr($canonicalizedQueryString, 1));
        //echo "<br>".$stringToSign."<br>";
        // 计算签名，注意accessKeySecret后面要加上字符'&'
        $signature = base64_encode(hash_hmac('sha1', $stringToSign, $accessKeySecret . '&', true));
        return $signature;
    }

    function do_get($app_key, $app_secret, $request_host, $request_uri, $request_method, $request_paras, &$info)
    {
        ksort($request_paras);
        $request_header_accept = "application/json;charset=utf-8";
        $content_type = "";
        $headers = array(
            'X-Ca-Key' => $app_key,
            'Accept' => $request_header_accept
        );
        ksort($headers);
        $header_str = "";
        $header_ignore_list = array('X-CA-SIGNATURE', 'X-CA-SIGNATURE-HEADERS', 'ACCEPT', 'CONTENT-MD5', 'CONTENT-TYPE', 'DATE');
        $sig_header = array();
        foreach ($headers as $k => $v) {
            if (in_array(strtoupper($k), $header_ignore_list)) {
                continue;
            }
            $header_str .= $k . ':' . $v . "\n";
            array_push($sig_header, $k);
        }
        $url_str = $request_uri;
        $para_array = array();
        foreach ($request_paras as $k => $v) {
            array_push($para_array, $k . '=' . $v);
        }
        if (!empty($para_array)) {
            $url_str .= '?' . join('&', $para_array);
        }
        $content_md5 = "";
        $date = "";
        $sign_str = "";
        $sign_str .= $request_method . "\n";
        $sign_str .= $request_header_accept . "\n";
        $sign_str .= $content_md5 . "\n";
        $sign_str .= "\n";
        $sign_str .= $date . "\n";
        $sign_str .= $header_str;
        $sign_str .= $url_str;

        $sign = base64_encode(hash_hmac('sha256', $sign_str, $app_secret, true));
        $headers['X-Ca-Signature'] = $sign;
        $headers['X-Ca-Signature-Headers'] = join(',', $sig_header);
        $request_header = array();
        foreach ($headers as $k => $v) {
            array_push($request_header, $k . ': ' . $v);
        }

        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $request_host . $url_str);
        //curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLINFO_HEADER_OUT, true);
        curl_setopt($ch, CURLOPT_VERBOSE, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $request_header);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $ret = curl_exec($ch);
        $info = curl_getinfo($ch);
        curl_close($ch);
        return $ret;
    }

    function https_request($url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $data = curl_exec($curl);
        if (curl_errno($curl)) {
            return 'ERROR ' . curl_error($curl);
        }
        curl_close($curl);
        return $data;
    }

    function xml_to_array($xml)
    {
        $reg = "/<(\w+)[^>]*>([\\x00-\\xFF]*)<\\/\\1>/";
        if (preg_match_all($reg, $xml, $matches)) {
            $count = count($matches[0]);
            for ($i = 0; $i < $count; $i++) {
                $subxml = $matches[2][$i];
                $key = $matches[1][$i];
                if (preg_match($reg, $subxml)) {
                    $arr[$key] = $this->xml_to_array($subxml);
                } else {
                    $arr[$key] = $subxml;
                }
            }
        }
        return @$arr;
    }


}
